function CalculateIntensityForFolder(sDir )
%Uses McIntensity plugin in Imaris to calculate intenisities for a whole folder

    %Function that goes through all the folders
    function GrabFolder(sDir)
        %Go through directory
        lFiles = dir(sDir);
        for iFile=1:length(lFiles)
            sFilename = lFiles(iFile).name;
            %Ignore . and ..
            if (strcmp(sFilename,'.') || strcmp(sFilename,'..'))
                continue;
            %Enter subdirs
            elseif (lFiles(iFile).isdir)
                GrabFolder([sDir '\' sFilename]);
            %Open imaris files named with surface
            elseif (strcmp(sFilename(end-3:end),'.ims') && ~isempty(strfind(sFilename,'surface')) )
                %Try to open file, if not display error
                sImarisFile=[sDir '\' sFilename];
                try
                    %Start Imaris
                    apImaris = actxserver('Imaris.Application');
                    apImaris.mVisible = true;
                    apImaris.FileOpen(sImarisFile);
                    %Display time and file
                    disp([datestr(now,'HH:MM') ' ' sImarisFile]);
                catch struError
                    disp(['Imaris ' struError.message]);
                    continue;
                end;

                %Test whether we opened the file
                if ( ~isequal(apImaris.GetCurrentFileName,sImarisFile) )
                    disp(['Can''t open file: ' sTempFile]);
                else
                    try
                        MGIntensity(apImaris,true);
                        clear apImaris;
                    catch struError
                        disp(['Plugin ' struError.message]);
                        disp([sDir '\' sFilename]);
                        clear apImaris;
                        continue;
                    end;
                end;
            end;
        end;
    end


    %Did we set a directory or should the user choose one manually
    if(~exist('sDir','var'))
        sDir = uigetdir('C:\','Choose the parent folder for the creation of Excel files from Imaris surfaces');
        if (isequal(sDir,0))
            return;
        end;
    end;
    if ~isdir(sDir)
        return;
    end;
    %Add plugin path to search folder
    addpath('C:\Program Files\Bitplane\Imaris x64 7.1.1\XTensions');
    GrabFolder(sDir);
end